/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-12-28
*/
package com.rzico.account.service;

import com.rzico.account.model.CardCheckVo;
import com.rzico.account.model.CardExtVo;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.account.entity.CardCheck;
import com.rzico.basics.entity.*;
import com.rzico.core.service.SysSequenceService;
import com.rzico.util.DateUtils;
import com.rzico.util.StringUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.rzico.account.mapper.CardCheckMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <pre>
 * 充值卡审核业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class CardCheckService extends BaseServiceImpl<CardCheck, String> {

    @Autowired
    private CardCheckMapper cardCheckMapper;

    @Autowired @Lazy
    private SysSequenceService sysSequenceService;

    @Autowired
    private CardBillService cardBillService;


    @Override
    public BaseMapper<CardCheck, String> getMapper() {
        return cardCheckMapper;
    }


    /**
     * 查询未审批的卡审核批次号
     * @param params
     * @return
     */
    public List<String> selectUnCheckCode(Map<String, Object> params){
        return cardCheckMapper.selectUnCheckCode(params);
    }

    /**
     * 查询卡审核批次号充值信息
     * @param params
     * @return
     */
    public CardCheckVo selectUploadInfo(Map<String, Object> params){
        return cardCheckMapper.selectUploadInfo(params);
    }

    /**
     * 确认充值
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> confirmUpload(Map<String, Object> params, Enterprise enterprise){
        List<CardExtVo> dataList = new ArrayList<CardExtVo>();
        int affectCount = 0;
        String code = sysSequenceService.generate("card");
        Long companyId = null;
        Integer cardType = null;
        String memo = null;
        String startDate = null;
        String endDate = null;
        Long[] tagIds = null;
        List<CardCheck> cardCheckList = cardCheckMapper.selectList(params);
        for (CardCheck cardCheck : cardCheckList) {
            //设置所有充值用户信息
            CardExtVo cardExtVo = new CardExtVo();
            cardExtVo.setAmount(cardCheck.getBalance());
            cardExtVo.setName(cardCheck.getName());
            cardExtVo.setMobile(cardCheck.getMobile());
            dataList.add(cardExtVo);
            if (null == companyId) {
                companyId = cardCheck.getCompanyId();
            }
            if (null == cardType) {
                cardType = cardCheck.getCardType();
            }
            if (StringUtils.isEmpty(memo)) {
                memo = cardCheck.getMemo();
            }
            if (StringUtils.isEmpty(startDate)) {
                startDate = DateUtils.getDateStr(cardCheck.getStartDate(), DateUtils.HYPHEN_DISPLAY_DATE);
            }
            if (StringUtils.isEmpty(endDate)) {
                endDate = DateUtils.getDateStr(cardCheck.getEndDate(), DateUtils.HYPHEN_DISPLAY_DATE);
            }
            if (null == tagIds && StringUtils.isNotEmpty(cardCheck.getTagids())) {
                String[] tagidsArr = cardCheck.getTagids().split(",");
                tagIds = new Long[tagidsArr.length];
                for(int i = 0; i < tagidsArr.length; i ++){
                    tagIds[i] = new Long(tagidsArr[i]);
                }
            }
            //更新卡审核记录
            cardCheck.setModifyDate(new Date());
            cardCheck.setState(true);
            cardCheck.setResult(true);
            affectCount += cardCheckMapper.updateByPrimaryKeySelective(cardCheck);
        }
        cardBillService.upload(dataList, enterprise.getId(), companyId, cardType, code, memo, startDate, endDate, tagIds, enterprise.getMchId());
        Map<String, Object> result = new HashMap<String, Object>();
        if (0 < affectCount) {
            result.put("returnCode", "success");
        } else {
            result.put("returnCode", "fail");
        }
        return result;
    }

    /**
     * 取消充值
     * @param params
     * @return
     */
    public List<CardCheck> cancelUpload(Map<String, Object> params){
        List<CardCheck> cList = new ArrayList<CardCheck>();
        List<CardCheck> cardCheckList = cardCheckMapper.selectList(params);
        for (CardCheck cardCheck : cardCheckList) {
            cardCheck.setModifyDate(new Date());
            cardCheck.setState(true);
            cardCheck.setResult(false);
            cardCheckMapper.updateByPrimaryKeySelective(cardCheck);
            cList.add(cardCheck);
        }
        return cList;
    }

    /**
     * 充值申请
     * @param dataList
     * @param enterpriseId
     * @param companyId
     * @param cardType
     * @param code
     * @param memo
     * @param startDate
     * @param endDate
     * @param tagIds
     * @param mchId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<CardCheck> uploadApply(List<CardExtVo> dataList, Long enterpriseId, Long companyId, Integer cardType, String code,
                                  String memo, String startDate, String endDate, Long[] tagIds, String mchId){
        List<CardCheck> cList = new ArrayList<CardCheck>();
        /*
         * 判断充值的金额类型，分存储卡和福利金
         * 若为存储卡，则先查找卡记录，若未存在，则需先建卡充值并生成流水记录，若已存在则更新金额，再生成流水记录
         * 若为福利卡，则直接建卡，生成流水记录
         */

        Date createDate = new Date();
        for (CardExtVo cardExtVo : dataList) {
            CardCheck cardCheck = new CardCheck();
            cardCheck.setCreateDate(createDate);//开始时间
            cardCheck.setModifyDate(createDate);//更新时间
            cardCheck.setDeleted(false);//未删除
            cardCheck.setBalance(cardExtVo.getAmount());//余额
            cardCheck.setCode(code);//审批批次号
            cardCheck.setMobile(cardExtVo.getMobile());
            cardCheck.setName(cardExtVo.getName());
            cardCheck.setMemo(memo);//卡备注
            cardCheck.setState(false);//审核状态
            cardCheck.setEnterpriseId(enterpriseId);
            if (0 == cardType) {
                cardCheck.setCardType(0);
            } else {
                cardCheck.setCompanyId(companyId);
                cardCheck.setStartDate(DateUtils.getDate(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                cardCheck.setEndDate(DateUtils.getDate(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
                cardCheck.setCardType(1);
                //设置卡的标签
                if (tagIds!=null) {
                    StringBuffer tag = new StringBuffer();
                    for (int i = 0; i < tagIds.length; i ++) {
                        if (i == tagIds.length - 1) {
                            tag.append(tagIds[i]);
                        } else {
                            tag.append(tagIds[i] + ",");
                        }
                    }
                    cardCheck.setTagids(tag.toString());
                }

            }
            cardCheckMapper.insertUseGeneratedKeys(cardCheck);
            cList.add(cardCheck);
        }

        return cList;

    }

}
